using System.Collections;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class UiMainMenu : MonoBehaviour
{
    [SerializeField] private string sceneName = "MainScene";
    private CanvasGroup canvasGroup;
    private Button continueButton;
    private Button newGameButton;
    private Button exitGameButton;
    private UiFadeScreen fadeScreen;

    private void Awake()
    {
        canvasGroup = GetComponentInChildren<CanvasGroup>();
        continueButton = canvasGroup.transform.Find("Continue").GetComponent<Button>();
        newGameButton = canvasGroup.transform.Find("NewGame").GetComponent<Button>();
        exitGameButton = canvasGroup.transform.Find("ExitGame").GetComponent<Button>();
        fadeScreen = GetComponentInChildren<UiFadeScreen>();
    }

    private void Start()
    {
        continueButton.onClick.AddListener(Continue);
        newGameButton.onClick.AddListener(New);
        exitGameButton.onClick.AddListener(Exit);
        continueButton.interactable = SaveManager.Instance.HasSaveData();
    }

    public void Continue()
    {
        Debug.Log("Continuing game...");
        canvasGroup.blocksRaycasts = false;
        _ = StartCoroutine(LoadSceneWithFadeEffect());
    }

    private void New()
    {
        Debug.Log("Starting new game...");
        canvasGroup.blocksRaycasts = false;
        SaveManager.Instance.DeleteSaveData();
        _ = StartCoroutine(LoadSceneWithFadeEffect());
    }

    private void Exit()
    {
        canvasGroup.blocksRaycasts = false;
#if UNITY_EDITOR
        Debug.Log("Exiting game...");
        return;
#elif !UNITY_EDITOR
        Application.Quit();
#endif
    }

    private IEnumerator LoadSceneWithFadeEffect()
    {
        fadeScreen.FadeOut();
        float seconds = fadeScreen.Anim.GetCurrentAnimatorClipInfo(0).Length;
        Debug.Log($"Fade out duration: {seconds} seconds");
        yield return new WaitForSeconds(seconds);
        SceneManager.LoadScene(sceneName);
    }

    private IEnumerator LoadSceneWithFadeEffect(float delay)
    {
        fadeScreen.FadeOut();
        yield return new WaitForSeconds(delay);
        SceneManager.LoadScene(sceneName);
    }
}
